package com.ccnode.codegenerator.taikaoback.controller;

import com.ccnode.codegenerator.taikaoback.entity.Request.SendSmsRequest;
import com.ccnode.codegenerator.taikaoback.service.SmsService;
import com.ccnode.codegenerator.taikaoback.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信验证码控制器
 */
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     * @param request 包含手机号的请求
     * @return 发送结果
     */
    @PostMapping("/send-code")
    public R<String> sendSmsCode(@RequestBody SendSmsRequest request) {
        // 验证手机号格式
        if (!isValidPhoneNumber(request.getPhoneNumber())) {
            return R.error(400, "手机号格式不正确");
        }

        // 发送6位验证码
        String code = smsService.sendSixDigitSmsCode(request.getPhoneNumber());

        if (code != null) {
            try {
                // 使用手机号作为key存储验证码，提高安全性
                stringRedisTemplate.opsForValue().set("SMS_CODE:" + request.getPhoneNumber(), code, 5, TimeUnit.MINUTES);
                return R.success("验证码发送成功", code);
            } catch (Exception e) {
                return R.error(500, "验证码存储失败");
            }
        } else {
            return R.error(500, "验证码发送失败，请稍后重试");
        }
    }

    /**
     * 简单的手机号验证
     */
    private boolean isValidPhoneNumber(String phoneNumber) {
        return phoneNumber != null && phoneNumber.matches("^1[3-9]\\d{9}$");
    }
}